package com.atguigu.daijia.driver.service.impl;

import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.driver.config.TencentCloudProperties;
import com.atguigu.daijia.driver.service.CiService;
import com.atguigu.daijia.driver.service.CosService;
import com.atguigu.daijia.model.vo.driver.CosUploadVo;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class CosServiceImpl implements CosService {

	@Autowired
	private TencentCloudProperties tencentCloudProperties;

	@Autowired
	private CiService ciService;

	/**
	 * 上传文件到腾讯云COS
	 *
	 * @param file  需要上传的文件
	 * @param path  文件上传的路径
	 * @return      返回上传后的文件信息
	 */
	@Override
	public CosUploadVo upload(MultipartFile file, String path) {
	    // 获取cosClient
	    COSClient cosClient = this.getCosClient();
	    // 文件上传
	    // 元数据信息
	    ObjectMetadata meta = new ObjectMetadata();
	    meta.setContentLength(file.getSize());
	    meta.setContentEncoding("UTF-8");
	    meta.setContentType(file.getContentType());

	    // 向存储桶中保存文件
	    String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")); // 文件后缀名
	    String uploadPath = "/driver/" + path + "/" + UUID.randomUUID().toString().replaceAll("-", "") + fileType;
	    // 示例：01.jpg -> /driver/auth/0o98754.jpg
	    PutObjectRequest putObjectRequest = null;
	    try {
	        // 初始化上传请求
	        putObjectRequest = new PutObjectRequest(tencentCloudProperties.getBucketPrivate(),
	                uploadPath,
	                file.getInputStream(),
	                meta);
	    } catch (IOException e) {
	        throw new RuntimeException(e);
	    }
	    putObjectRequest.setStorageClass(StorageClass.Standard);
	    PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest); // 上传文件
	    cosClient.shutdown(); // 关闭cosClient

		//图片审核
		Boolean imageAuditing = ciService.imageAuditing(uploadPath);
		if(!imageAuditing) {
			//删除违规图片
			cosClient.deleteObject(tencentCloudProperties.getBucketPrivate(),uploadPath);
			throw new GuiguException(ResultCodeEnum.IMAGE_AUDITION_FAIL);
		}

	    // 返回vo对象
	    CosUploadVo cosUploadVo = new CosUploadVo();
	    cosUploadVo.setUrl(uploadPath);
	    // 图片临时访问url，回显使用
	    String imageUrl = this.getImageUrl(uploadPath);
	    cosUploadVo.setShowUrl(imageUrl);
	    return cosUploadVo;
	}

	/**
	 * 获取COS客户端实例
	 * 本方法用于创建并配置COS客户端，使其能连接到腾讯云对象存储服务
	 *
	 * @return 初始化配置并返回COSClient实例
	 */
	public COSClient getCosClient(){
	    // 初始化用户身份信息（secretId, secretKey）。
	    String secretId = tencentCloudProperties.getSecretId();
	    String secretKey = tencentCloudProperties.getSecretKey();
	    COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);

	    // 设置 bucket 的地域, COS 地域
	    Region region = new Region(tencentCloudProperties.getRegion());
	    ClientConfig clientConfig = new ClientConfig(region);

	    // 建议设置使用 https 协议
	    clientConfig.setHttpProtocol(HttpProtocol.https);

	    // 生成 cos 客户端并返回
	    COSClient cosClient = new COSClient(cred, clientConfig);
	    return cosClient;
	}

	// 获取临时签名URL
	@Override
	public String getImageUrl(String path) {
	    // 如果路径为空，则直接返回空字符串
	    if(!StringUtils.hasText(path)) return "";

	    // 获取COS客户端实例
	    COSClient cosClient = this.getCosClient();

	    // 创建生成预签名URL的请求对象
	    GeneratePresignedUrlRequest request =
	            new GeneratePresignedUrlRequest(tencentCloudProperties.getBucketPrivate(), path, HttpMethodName.GET);

	    // 设置临时URL的有效期为15分钟
	    Date expiration = new DateTime().plusMinutes(15).toDate();
	    request.setExpiration(expiration);

	    // 生成预签名URL
	    URL url = cosClient.generatePresignedUrl(request);

	    // 关闭COS客户端实例
	    cosClient.shutdown();

	    // 返回预签名URL字符串
	    return url.toString();
	}
}
